<template>
  <el-dialog title="配置权限"
             :model-value="modelValue"
             @close="closed"
  >
    <el-tree ref="treeRef"
             :data="allPermission"
             :props="defaultProps"
             node-key="id"
             show-checkbox
             check-strictly
             default-expand-all
    >
    </el-tree>
    <template #footer>
      <el-button @click="closed">取消</el-button>
      <el-button type="primary" @click="onComfirm">确认</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue'
import { permissionList } from '../../../../api/permission'
import { updateResource, rolePermission } from '../../../../api/role'
import { watchSwitchLang } from '../../../../utils/i18n'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String,
    required: true
  }
})
const emits = defineEmits(['update:modelValue', 'updatePermission'])
const onComfirm = async () => {
  await updateResource(props.roleId, treeRef.value.getCheckedKeys())
  // 角色更新成功!
  emits('updatePermission')
  closed()
}
const closed = () => {
  emits('update:modelValue', false)
}
// 所有角色
const allPermission = ref([])
const getListData = async () => {
  allPermission.value = await permissionList()
}
getListData()
watchSwitchLang(getListData())
// ref
const treeRef = ref(null)
// 属性结构配置
const defaultProps = {
  children: 'children',
  label: 'name'
}
// 当前用户角色
// const roleResourceId = ref([])
const getRolePermission = async () => {
  const checkedKeys = await rolePermission(props.roleId)
  // roleResourceId.value = res.map(item => item.id)
  treeRef.value.setCheckedKeys(checkedKeys)
}
watch(() => props.roleId, value => {
  if (value) getRolePermission()
})
</script>
